$(document).ready(function () {

    $("#storeSelect").selectpicker();
    $("#employeeSelect").selectpicker();
    $("#accountMoneySelect").selectpicker();
    $("#customerSelect").selectpicker();
    $('#inputOrderTable').DataTable({
        destroy: true,
        searching: false,
        paging: true,//表格分页
        lengthChange: false
    });
    $('#productTable').DataTable({
        destroy: true,
        searching: false,
        paging: false,//表格分页
        lengthChange: false
    });
    toastr.options = {
        "closeButton": true,
        "debug": false,
        "progressBar": true,
        "positionClass": "toast-top-right",
        "onclick": null,
        "showDuration": "400",
        "hideDuration": "1000",
        "timeOut": "7000",
        "extendedTimeOut": "1000",
        "showEasing": "swing",
        "hideEasing": "linear",
        "showMethod": "fadeIn",
        "hideMethod": "fadeOut"
    }

    setInputOrderNumber($("#inputOrderNumber"))
    setInputOrderDate($("#inpDate"))
    listEmployees($("#employeeSelect"))
    listStores($("#storeSelect"))
    listMoneyAccount($("#accountMoneySelect"))
    listCustomer($("#customerSelect"))
    //失去焦点事件
    // $('#inputNumber' + product.id).blur(function (){
    //     //数量和进价相乘,设置到金额一列
    //
    //
    // })

});
let selects = [];
function listCustomer(obj) {
    $.ajax({
        type: 'get',
        url: "/admin/info/customer/list",
        dataType: 'json',
        success: function (data) {
            let select = obj;
            for (var i = 0; i < data.length; i++) {
                select.append('<option value="' + data[i].id + '" >' + data[i].name + '</option>');
            }
            select.selectpicker('refresh');
            select.selectpicker('render');
        }
    });
}


/**
 * 保存进货单据
 */
function showSaleOrderInfo() {
    let saleOrder = {}
    saleOrder.orderNumber = $('#inputOrderNumber').val()
    saleOrder.empId = $('#employeeSelect').val()
    saleOrder.price = $('#payMoney').val()
    saleOrder.cusId = $('#customerSelect').val()
    saleOrder.accId = $('#accountMoneySelect').val()
    saleOrder.inpDate = $("#inpDate").val()
    saleOrder.back = $('#backup').val()
    if (selects.length!==0){
        saleOrder.products = selects;
    }else{
        toastr.error('请添加商品后点击保存!','提示')
        return;
    }
    //商品信息
    console.log(saleOrder)
    $.ajax({
        type: 'post',
        url: "/admin/business/sale/save",
        dataType: 'json',
        contentType: 'application/json;charset=utf-8',
        data: JSON.stringify(saleOrder),
        success: function (resp) {
            console.log(resp)
            if (resp.data) {
                toastr.success(resp.message, '提示')
                setTimeout(function () {
                    window.location.reload()
                }, 2000)
            } else {
                toastr.error(resp.message, '提示')
            }
        }
    });
}


/**
 * 列出所有的支付账户信息
 */
function listMoneyAccount(obj) {
    $.ajax({
        type: 'get',
        url: "/admin/info/moneyAccount/list",
        dataType: 'json',
        success: function (data) {
            let select = obj;
            for (var i = 0; i < data.length; i++) {
                select.append('<option value="' + data[i].accId + '" >' + data[i].accName + '</option>');
            }
            select.selectpicker('refresh');
            select.selectpicker('render');
        }
    });
}

/**
 * 金额计算
 */
function payMoney() {
    let money = localStorage.getItem('payMoney')
    $('#payMoney').val(money)
    localStorage.removeItem('payMoney')
}

/**
 * 列出所有的库存地址
 * @param obj
 */
function listStores(obj) {
    $.ajax({
        type: 'get',
        url: "/admin/info/store/list",
        dataType: 'json',
        success: function (data) {
            let select = obj;
            for (var i = 0; i < data.length; i++) {
                select.append('<option value="' + data[i].bstoId + '" >' + data[i].bstoTitle + '</option>');
            }
            select.selectpicker('refresh');
            select.selectpicker('render');
        }
    });
}

/**
 * 列出所有的职工
 * @param obj
 */
function listEmployees(obj) {
    $.ajax({
        type: 'get',
        url: "/admin/info/employee/list",
        dataType: 'json',
        success: function (data) {
            let select = obj;
            for (var i = 0; i < data.length; i++) {
                select.append('<option value="' + data[i].id + '" >' + data[i].name + '</option>');
            }
            select.selectpicker('refresh');
            select.selectpicker('render');
        }
    });
}

/**
 * 默认进货日期
 * @param obj
 */
function setInputOrderDate(obj) {
    let date = new Date();
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    if (month < 10) {
        month = "0" + month;
    }
    if (day < 10) {
        day = "0" + day;
    }
    obj.val(year + '-' + month + '-' + day)
}

/**
 * 设置单据编号
 */
function setInputOrderNumber(obj) {
    //日期格式化为指定格式
    Date.prototype.format = function (fmt) {
        var o = {
            "M+": this.getMonth() + 1,                 //月份
            "d+": this.getDate(),                    //日
            "h+": this.getHours(),                   //小时
            "m+": this.getMinutes(),                 //分
            "s+": this.getSeconds(),                 //秒
            "q+": Math.floor((this.getMonth() + 3) / 3), //季度
            "S": this.getMilliseconds()             //毫秒
        };

        if (/(y+)/.test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        }

        for (var k in o) {
            if (new RegExp("(" + k + ")").test(fmt)) {
                fmt = fmt.replace(
                    RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            }
        }

        return fmt;
    }
    obj.val(new Date().format("yyyyMMddhhmmss"))
}

/**
 * 获得所有商品到列表中
 */
function getAllProducts() {
    $.get("/admin/business/storage/product/listAll", {}, function (resp) {
        //保存到localStore中
        console.log(resp)
        //渲染datatabls表格
        $("#productTable").DataTable({
            destroy: true,
            //数据源
            data: resp,
            //取消搜索栏
            bFilter: false,
            paging: false,
            bLengthChange: false,
            //给每列赋值
            columns: [
                {
                    data: 'id', render: function (data, type, row, meta) {
                        return '<input name="inp-product-box" class="inp-product-box" type="checkbox" value="' + row.id + '">'
                    }
                },
                {
                    data: 'id', render: function (data, type, row, meta) {
                        return '<span id="proId' + row.id + '">' + row.id + '</span>';
                    }
                },
                {
                    data: 'proTitle', render: function (data, type, row) {
                        return '<span id="proTitle' + row.id + '">' + row.proTitle + '</span>';
                    }
                },
                {
                    data: 'proUnit', render: function (data, type, row) {
                        return '<span id="proUnit' + row.id + '">' + row.proUnit + '</span>';
                    }
                },


                {
                    data: 'proPrice', render: function (data, type, row, meta) {
                        return ' <input type="text" class="form-control" id="proPrice' + row.id + '" value="' + row.proPrice + '" placeholder="请输入进价">';
                    }
                },
                {
                    data: 'proNum', render: function (data, type, row) {
                        return ' <input type="text" class="form-control" id="proNum' + row.id + '" placeholder="请输入进货数量">';
                    }
                },
                {
                    data: 'proNum', render: function (data, type, row) {
                        return '<span id="storage' + row.id + '">' + row.proNum + '</span>';
                    }
                },
            ],


        })
    })
}

/**
 * 添加商品到进货单
 */
function save2OrderList() {

    let count = 0;
    // $("#productTable").dataTable().fnGetNodes()[1].firstElementChild.firstElementChild.outerHTML
    // var tbl = $("#productTable").dataTable();
    // var trList = tbl.fnGetNodes();
    // for(i=0;i<trList.length;i++){
    //     var trObj = trList[i];
    //     //接下来就和 案1 的一样了 就只写个输出 不做实现了
    //     console.log(trObj.firstElementChild.firstElementChild.checked);
    // }
    // $("#productTable").dataTable().fnGetNodes()[1].innerHTML.getElementsByClassName
    $("input[name='inp-product-box']:checked").each(function () {
        const product = {};
        if ($(this).prop('checked')) {
            //如果当前属性为checked
            product.id = $(this).val()
            product.proTitle = $('#proTitle' + product.id).text()
            product.proUnit = $('#proUnit' + product.id).text()
            product.proPrice = $('#proPrice' + product.id).val()
            product.proNum = $('#proNum' + product.id).val()
            product.storage = $('#storage' + product.id).text()
            if (product.proPrice.length === 0) {
                toastr.error('请输入进价', '提示')
                $('#inputPrice' + product.id).focus()
                return 0;
            }
            product.eachSum = parseFloat(product.proPrice) * parseFloat(product.proNum)
            count += product.eachSum
            selects.push(product)
        }
    });
    if (selects.length === 0) {
        swal("您没有选中任何数据，请选中后重试！");
    }
    //保存到localstore中
    console.log(selects)
    $("#myModal").modal('hide')
    $("#inputOrderTable").DataTable({
        destroy: true,
        //数据源
        data: selects,
        //取消搜索栏
        bFilter: false,
        paging:false,
        bLengthChange: false,
        //给每列赋值
        columns: [
            {
                data: 'id', render: function (data, type, row, meta) {
                    return row.id;
                }
            },
            {
                data: 'proTitle', render: function (data, type, row) {
                    return row.proTitle === null || row.proTitle === undefined ? "" : row.proTitle;
                }
            },
            {
                data: 'proUnit', render: function (data, type, row) {
                    return row.proUnit === null || row.proUnit === undefined ? "" : row.proUnit;
                }
            },

            {
                data: 'proNum', render: function (data, type, row) {
                    return row.proNum === null || row.proNum === undefined ? "暂无" : row.proNum;
                }
            },
            {
                data: 'proPrice', render: function (data, type, row, meta) {
                    return row.proPrice === null || row.proPrice === undefined ? "暂无" : row.proPrice;
                }
            },

            {
                data: 'eachSum', render: function (data, type, row) {
                    return row.eachSum === null || row.eachSum === undefined ? "暂无" : row.eachSum;
                }
            },
        ],
    });
    $("#payMoney").val(count)


}


// localStorage.setItem("products",JSON.stringify(selects))
// $.ajax({
//     type: 'post',
//     url: "/admin/business/inputOrder/show2Table",
//     dataType: 'json',
//     contentType: 'application/json;charset=utf-8',
//     data: JSON.stringify(selects),
//     success: function (resp) {
//
// });

